import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:gzmall_app/model/p_option_type.dart';
import 'package:gzmall_app/model/p_option_value.dart';
import 'package:gzmall_app/model/p_skus.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/model/shopping_cart.dart';
import 'package:gzmall_app/shoppping_cart/confirm_order.dart';

class GoodsSkusWidget extends StatefulWidget {
  List<POptionType> pOptionTypeList;
  List<PSkus> pSkusList;
  Function onSelectSku;
  String productName;
  String shopName;
  int stock;
  PSkus pSkus;
  int quantity = 1;

  GoodsSkusWidget(this.pOptionTypeList, this.pSkusList, this.onSelectSku,
      this.productName, this.shopName, this.stock, this.pSkus, this.quantity);

  @override
  State<StatefulWidget> createState() => GoodsSkusWidgetState(pOptionTypeList,
      pSkusList, onSelectSku, productName, shopName, stock, pSkus, quantity);
}

class GoodsSkusWidgetState extends State<GoodsSkusWidget> {
  List<POptionType> pOptionTypeList;
  List<PSkus> pSkusList;
  Function onSelectSku;
  String productName;
  String shopName;
  int stock;
  PSkus pSkus;
  int quantity = 1;

  List<Widget> _skuWidgget = [];

  Map<int, POptionValue> _selectSku = Map();
  PSkus _sSku;

  GoodsSkusWidgetState(this.pOptionTypeList, this.pSkusList, this.onSelectSku,
      this.productName, this.shopName, this.stock, this.pSkus, this.quantity);

  @override
  void initState() {
    super.initState();
    if (pOptionTypeList != null && pOptionTypeList.length > 0) {
      for (var optionType in pOptionTypeList) {
        if (optionType.optionValue != null &&
            optionType.optionValue.length > 0) {
          POptionValue selectValue = optionType.optionValue[0];
          if (pSkus != null &&
              pSkus.optionValues != null &&
              pSkus.optionValues.length > 0) {
            bool isGet = false;
            for (var v in optionType.optionValue) {
              if (isGet) {
                break;
              }
              for (var sv in pSkus.optionValues) {
                if (v.id == sv.id) {
                  selectValue = v;
                  isGet = true;
                  break;
                }
              }
            }
          }
          if (optionType != null && selectValue != null) {
            _selectSkuAction(optionType.id, selectValue.id);
          }
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (pOptionTypeList != null && pOptionTypeList.length > 0) {
      _skuWidgget =
          pOptionTypeList.map((item) => _createSkusWidget(item)).toList();
    } else {
      _skuWidgget.add(Container());
    }
    String _selectSkuValueStr = "已选:";
    if (_sSku != null &&
        _sSku.optionValues != null &&
        _sSku.optionValues.length > 0) {
      for (var item in _sSku.optionValues) {
        _selectSkuValueStr =
            _selectSkuValueStr + "\"" + item.presentation + "\" ";
      }
    }
    return Column(children: <Widget>[
      GestureDetector(
        child: Container(
          color: ColorCommon.translucent2,
          height: 100.0,
        ),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      Expanded(
        child: Container(
          color: Colors.white,
          padding: const EdgeInsets.all(15.0),
          child: Column(children: <Widget>[
            Container(
              margin: const EdgeInsets.only(bottom: 10.0),
              child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    _sSku != null && _sSku.avatar != null
                        ? CachedNetworkImage(
                            imageUrl: _sSku.avatar,
                            fit: BoxFit.fill,
                            width: 100.0,
                            height: 100.0,
                          )
                        : Container(
                            width: 100.0,
                            height: 100.0,
                            color: Colors.grey,
                          ),
                    Expanded(
                      child: Container(
                        margin: const EdgeInsets.only(left: 10.0),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(
                              "¥" +
                                  (_sSku != null ? _sSku.salePrice ?? '' : ''),
                              style: TextStyle(
                                  fontSize: 16.0, color: ColorCommon.primaryColor),
                            ),
                            Padding(
                              padding: const EdgeInsets.only(top: 2.0),
                              child: Text(
                                "库存" +
                                    (_sSku != null
                                        ? _sSku.onHandCount ?? ''
                                        : '0') +
                                    "件",
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: 14.0, color: ColorCommon.grey3),
                              ),
                            ),
                            Text(
                              _selectSkuValueStr,
                              style: TextStyle(
                                  fontSize: 14.0, color: ColorCommon.black1),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ]),
            ),
            Expanded(
              child: ListView(children: _skuWidgget),
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    "购买数量",
                    style: TextStyle(fontSize: 16.0, color: ColorCommon.grey8),
                  ),
                ),
                Row(
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        if (this.quantity > 1) {
                          if (!mounted) return;
                          setState(() {
                            this.quantity--;
                          });
                        }
                      },
                      child: Container(
                        width: 37.0,
                        height: 30.0,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: ColorCommon.grey2,
                        ),
                        child: Text(
                          "-",
                          style: TextStyle(fontSize: 16.0),
                        ),
                      ),
                    ),
                    Container(
                      width: 45.0,
                      height: 30.0,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: ColorCommon.grey2,
                      ),
                      child: Text(this.quantity.toString()),
                    ),
                    GestureDetector(
                      onTap: () {
                        if (!mounted) return;
                        setState(() {
                          this.quantity++;
                        });
                      },
                      child: Container(
                        width: 37.0,
                        height: 30.0,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: ColorCommon.grey2,
                        ),
                        child: Text(
                          "+",
                          style: TextStyle(fontSize: 16.0),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10.0),
              alignment: Alignment.center,
              child: Row(children: <Widget>[
                Expanded(
                  child: InkWell(
                    onTap: () {
                      if (stock != null && stock > 0 && _sSku != null) {
                        _addShopCart(_sSku.id, this.quantity);
                      } else {
                        ToastUtil.showMessageToast("库存不足或者商品数据有误");
                      }
                    },
                    child: Container(
                      height: 50.0,
                      width: 100.0,
                      alignment: Alignment.center,
                      decoration: new BoxDecoration(
                          color: Colors.orange,
                          borderRadius: new BorderRadius.only(
                              topLeft: Radius.circular(100.0),
                              bottomLeft: Radius.circular(100.0),
                              topRight: Radius.circular(0.0),
                              bottomRight: Radius.circular(0.0))),
                      child: new Text(
                        "购物车",
                        style: TextStyle(fontSize: 15.0, color: Colors.white),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: InkWell(
                    onTap: () {
                      if (stock != null && stock > 0 && _sSku != null) {
                        OrderItem orderItem = OrderItem(
                            0,
                            this.quantity,
                            productName,
                            _selectSkuValueStr,
                            _sSku.salePrice,
                            _sSku.skuImages,
                            _sSku.id,
                            "",
                            "",
                            _sSku.avatar);
                        List<OrderItem> orderItems = [];
                        orderItems.add(orderItem);
                        ShoppingCart cart = ShoppingCart(shopName, orderItems);
                        List<ShoppingCart> shoppingCartList = [];
                        shoppingCartList.add(cart);

                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (_) {
                          return ConfirmOrderPage(
                            shoppingCartList: shoppingCartList,
                            skuId: _sSku.id,
                            quantity: this.quantity,
                          );
                        }));
                      } else {
                        ToastUtil.showMessageToast("库存不足或者商品数据有误");
                      }
                    },
                    child: Container(
                      height: 50.0,
                      width: 100.0,
                      alignment: Alignment.center,
                      decoration: new BoxDecoration(
                          color: Colors.red,
                          borderRadius: new BorderRadius.only(
                              topLeft: Radius.circular(0.0),
                              bottomLeft: Radius.circular(0.0),
                              topRight: Radius.circular(100.0),
                              bottomRight: Radius.circular(100.0))),
                      child: new Text(
                        "立即购买",
                        style: TextStyle(fontSize: 15.0, color: Colors.white),
                      ),
                    ),
                  ),
                ),
              ]),
            ),
          ]),
        ),
      ),
    ]);
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 13.0, color: textColor),
      ),
    );
  }

  Widget _createSkusWidget(POptionType sku) {
    List<Widget> skuValues = [];
    if (sku.optionValue != null && sku.optionValue.length > 0) {
      skuValues = sku.optionValue
          .map((item) => InkWell(
                child: item.isSelect
                    ? _getTagView(item.presentation, Colors.white,
                        ColorCommon.primaryColor, ColorCommon.primaryColor)
                    : _getTagView(item.presentation, ColorCommon.grey5,
                        ColorCommon.grey5, ColorCommon.grey8),
                onTap: () {
                  if (!mounted) return;
                  setState(() {
                    _selectSkuAction(sku.id, item.id);
                  });
                },
              ))
          .toList();
    } else {
      skuValues.add(Align(child: Text("暂无规格")));
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          sku.name,
          style: TextStyle(fontSize: 16.0, color: ColorCommon.grey8),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 15.0, bottom: 15.0),
          child: Wrap(
            spacing: 10.0,
            runSpacing: 10.0,
            children: skuValues,
          ),
        ),
      ],
    );
  }

  _selectSkuAction(int skuId, int itemId) {
    for (var optionType in pOptionTypeList) {
      if (optionType.id == skuId &&
          optionType.optionValue != null &&
          optionType.optionValue.length > 0) {
        for (var i in optionType.optionValue) {
          if (i.id == itemId) {
            _selectSku[optionType.id] = i;
            i.isSelect = true;
          } else {
            i.isSelect = false;
          }
        }
        _sSku = _getSelectSkuValue();
        onSelectSku(_sSku, this.quantity);
        break;
      }
    }
  }

  PSkus _getSelectSkuValue() {
    for (var sku in pSkusList) {
      if (sku != null &&
          sku.optionValues != null &&
          sku.optionValues.length > 0) {
        Map<int, bool> _selectMap = Map();
        for (var sValue in sku.optionValues) {
          for (var v in _selectSku.values) {
            if (sValue.id == v.id) {
              _selectMap[sValue.id] = true;
              break;
            } else {
              _selectMap[sValue.id] = false;
            }
          }
        }
        if (_selectMap.containsValue(false)) continue;
        return sku;
      }
    }
    return null;
  }

  _addShopCart(int skuId, int quantity) {
    Map<String, String> params = {
      "sku_id": skuId.toString(),
      "quantity": quantity.toString(),
    };

    NetUtil.post(context, Api.orderItems, (data, message) {
      ToastUtil.showMessageToast(message);
    }, params: params, isShowLoading: true);
  }
}
